import { C41RefundList, Layout } from "@/components";
import {
  requestRefund,
  submitRefund,
  useUserInfo,
} from "@/store/userDataContext";
import { useEffect, useState } from "react";
import { useDidShow, redirectTo, useRouter, navigateBack } from "@tarojs/taro";
import { useAuth } from "@/store/authContext";
import { error } from "@/utils/alert";
import { requestSubscribeMessage } from "@/store/userDataContext";
import notifications from "@/data/notifications";

function Refund() {
  const { params } = useRouter();
  const { orderNo } = params;
  const { dispatchAuthAction } = useAuth();
  const { userInfoState } = useUserInfo();
  const [refundInfo, setRefundInfo] = useState<any>(null);
  const [refundReasons, setRefundReasons] = useState<null | string[]>(null);
  const { selectedRefundData } = userInfoState;

  useDidShow(async () => {
    if (orderNo) {
      const refundApi = await requestRefund({
        query: { orderNo: orderNo },
        authDispatch: dispatchAuthAction,
      });
      if (refundApi) {
        setRefundInfo(refundApi.orderRefundVoList);
        if (refundApi.refundReasonWap) {
          setRefundReasons(refundApi.refundReasonWap.split(/\n/));
        } else {
          setRefundReasons(["商品损坏"]);
        }
      }
    } else {
      navigateBack();
    }
  });

  useEffect(() => { }, [refundInfo]);

  const handleSubmitRefund = async (reason, additional) => {
    if (!reason) {
      error("理由不能为空");
      return false;
    }
    let merOrderNos = [];
    if (selectedRefundData && selectedRefundData.length) {
      merOrderNos = refundInfo
        .filter((ri: any) => selectedRefundData.includes(ri.productId))
        .map((mo: any) => mo.merOrderNo);
    }
    const query: any = {
      merOrderNos: merOrderNos,
      orderNo: orderNo,
      refundReasonWap: reason,
      refund_reason_wap_explain: additional,
    };

    const result = await submitRefund({
      query: query,
      authDispatch: dispatchAuthAction,
    });

    if (result) {
      requestSubscribeMessage([
        notifications.refund.reviewed,
        notifications.return.reviewed,
        notifications.refund.success,
      ]);
      setTimeout(() => {
        redirectTo({ url: `/pages/user-order-details/index?orderNo=${orderNo}` });
      }, 1000);
    }
  };

  return (
    <Layout>
      {refundInfo && refundReasons && (
        <C41RefundList
          items={refundInfo}
          refundReasons={refundReasons}
          handleSubmit={handleSubmitRefund}
        />
      )}
    </Layout>
  );
}

export default Refund;
